<script setup lang="ts">
import {useEmitt} from "@/hooks/web/useEmitt";
import {Vector3} from "three";

const emitt = useEmitt()

const isEdit = ref(false)
const position = ref<Vector3>()
const editPosition = ref({
  x: 0,
  y: 0,
  z: 0
})

watch(editPosition, ({x, y, z}) => {
  position.value!.set(x, y, z)
}, {deep: true})

const pollPosition = () => {
  requestAnimationFrame(() => {
    if (isEdit.value) {
      editPosition.value = {
        x: Number(position.value!.x.toFixed(1)),
        y: Number(position.value!.y.toFixed(1)),
        z: Number(position.value!.z.toFixed(1)),
      }
    }

    pollPosition()
  })
}

const edit = () => {
  emitt.emit('spawnPointEdit', position)
  isEdit.value = true
}

const confirm = () => {
  emitt.emit('spawnPointConfirm')
  isEdit.value = false
}

const cancel = () => {
  emitt.emit('spawnPointCancel')
  isEdit.value = false
}

onMounted(() => {
  pollPosition()
})

</script>

<template>
  <el-button type="primary" @click="edit">设置初始点位</el-button>

  <div v-if="isEdit" class="menu">
    <el-button type="primary" size="large" @click="confirm">
      设置初始点位
    </el-button>
    <el-button type="danger" size="large" @click="cancel">
      取消设置
    </el-button>

    <el-space class="flex text-base mx-2">
      <el-input-number
        style="width: 120px"
        v-model="editPosition.x"
        controls-position="right"
        :precisio="1"
        :step="0.1"
        step-strictly
      >
        <template #prefix>
          <div>x</div>
        </template>
      </el-input-number>
      <el-input-number
        style="width: 120px"
        v-model="editPosition.y"
        controls-position="right"
        :precisio="1"
        :step="0.1"
        step-strictly
      >
        <template #prefix>
          <div>y</div>
        </template>
      </el-input-number>
      <el-input-number
        style="width: 120px"
        v-model="editPosition.z"
        controls-position="right"
        :precisio="1"
        :step="0.1"
        step-strictly
      >
        <template #prefix>
          <div>z</div>
        </template>
      </el-input-number>
    </el-space>
  </div>
</template>

<style scoped lang="scss">
.menu {
  position: fixed;
  z-index: 100;

  width: 680px;
  height: 60px;
  background: white;
  border-radius: 8px;

  left: calc(50% - 340px);
  top: calc(120px);

  display: flex;
  justify-content: center;
  align-items: center;
  padding: 16px;
}
</style>
